/**
 * 通过seeker获得的数据，处理方法类似本地静态数据
 * TODO 添加method和简单的参数匹配模式，为同一接口添加不同的数据
 */
var $ = require('../util')
var config = require('../../config.json')
var seekerFile = 'server/seeker-data'
module.exports = function (router) {

  var dataList = []
  var routesList = []
  var dataFile = seekerFile
  $.walkFile(dataFile, dataList)
  for (let i in dataList) {
    let fl = dataList[i]
    let match = fl.match(/\/[^\/]+$/)
    if (match) {
      let name = match[0]
      let folder = fl.replace(dataFile, '').split('/')
      folder = folder.splice(0, folder.length - 1)
      let nameArr = name.split('.').slice(0, -1)
      let namePath = '/service/:app'
      let varCount = 0
      if (folder && folder.length) {
        namePath += folder.join('/')
      }
      for (let s in nameArr) {
        if (s > 0) namePath += '/'
        if (nameArr[s] === '#') {
          namePath += ':code_' + varCount++
        } else {
          namePath += nameArr[s]
        }
      }
      routesList.push({
        route: namePath,
        path: fl
      })
    }
  }

  // 生成路由函数
  for (let i in routesList) {
    let route = routesList[i]
    router.all(route.route, function (req, res, next) {
      if (!config.seeker_data) {
        return next()
      }
      console.log('READ SEEKER DATA: '.blue + route.path)
      res.send($.readJson(route.path))
    })
  }
}
